// pages/spray/deviceLogHistory.js
const app = getApp()
const utils = require('../../utils/util.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    skin: '',
    beginTime: '', // 开始日期
    endTime: '', // 结束日期
    areaId : '',
    page : 1,
    haveNext: false,
    dataList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.setNavBar()
    const { skin } = app.globalData
    console.log(options)
    this.setData({
      skin,
      areaId : options.areaId || 0,
    })
    this.loadList(1);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.haveNext) {
      this.setData({
        page: this.data.page + 1
      });
      this.loadList(this.data.page);
    }
  },

  loadList: function (page) {
    let that = this;
    let threeDay = utils.getDay(-1), 
      today = utils.getDay(0),
      getListParams = {
        "areaId" : that.data.areaId,
        "page": page,
        "pageSize": 20,
        "beginTime" : that.data.beginTime ? (that.data.beginTime + " 00:00:00") : (threeDay + " 00:00:00"),
        "endTime" : that.data.endTime ? (that.data.endTime + " 23:59:59") : (today + " 23:59:59")
      };
    utils.promiseGet('/wx/device/spray/getAreaTempDataPage', getListParams).then(res => {
      let list = that.data.dataList;
      let haveNext = that.data.haveNext;
      if (page == 1) {
        list = [];
      }
      if (res.code == 200) {
        let result = res.data;
        if (result.rows.length > 0) {
          for (let i = 0; i < result.rows.length; i++) {
            list.push(result.rows[i]);
          }
          haveNext = true;
        } else {
          haveNext = false;
        }
      } else {
      }
      this.setData({
        dataList: list,
        haveNext: haveNext
      });
    }).catch(e => {
      console.log(e);
    });
  },

  handleBeginTimeChange(e) {
    this.setData({
      beginTime: e.detail
    })

    this.handleTimeChange()
  },

  handleEndTimeChange(e) {
    this.setData({
      endTime: e.detail
    })

    this.handleTimeChange()
  },

  handleTimeChange() {
    const { beginTime, endTime } = this.data
    if (beginTime && endTime) {
      this.setData({
        page: 1
      });
      this.loadList(1);
    }
  }
})